package com.newcapec.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * HttpClient工具类
 *
 * @author steven
 */
public class HttpRequestUtils {
	/**
	 * 设置连接超时时间，单位毫秒。
	 * 	设置从connect Manager获取Connection 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
	 * 	请求获取数据的超时时间，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用
	 */
	static RequestConfig requestConfig = RequestConfig.custom()      
	        .setConnectTimeout(50000).setConnectionRequestTimeout(15000)
	        .setSocketTimeout(15000).build();

	/**
	 * get请求
	 */
	public static String httpGet(String url,CookieStore cookieStore){
		try {
			// 自定义HttpClient 设置CookieStore
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			HttpGet request = new HttpGet(url);
			request.setConfig(requestConfig);

			CloseableHttpResponse response = httpclient.execute(request);

			int status = response.getStatusLine().getStatusCode();
			if (status == HttpStatus.SC_OK) {
				return EntityUtils.toString(response.getEntity(), "UTF-8");
			}
			throw new RuntimeException("请求失败!");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * post请求
	 * 文件上传
	 */
	public static String httpPostMultipart(String url, MultipartEntityBuilder builder, JSONObject reqHeader){
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			
        	//自定义HttpClient 设置CookieStore
            HttpPost request = new HttpPost(url);
			request.setConfig(requestConfig);
			if (reqHeader != null && !reqHeader.isEmpty()) {
				Set<String> set = reqHeader.keySet();
				for (String key:set){
					request.setHeader(key,reqHeader.getString(key));
				}
	        }
            HttpEntity entity = builder.build();
            request.setEntity(entity);
			CloseableHttpResponse response = httpclient.execute(request);
			
			int status = response.getStatusLine().getStatusCode();
			HttpEntity responseEntity = response.getEntity();
			if (404 == status) {
				throw new RuntimeException("接口不存在!");
			}
			if (responseEntity != null) {
				return EntityUtils.toString(responseEntity, "UTF-8");
			}
			throw new RuntimeException("请求异常!");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * post请求
	 * 数据
	 */
	public static String httpPostForm(String url, JSONObject json, JSONObject reqHeader){
		try {
        	//自定义HttpClient 设置CookieStore
			CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost request = new HttpPost(url);
            //设置Content-Type
            request.setHeader("Content-Type", "application/x-www-form-urlencoded");
			request.setConfig(requestConfig);
	        if (reqHeader != null && !reqHeader.isEmpty()) {
				Set<String> set = reqHeader.keySet();
	           for (String key:set){
	            	request.setHeader(key,reqHeader.getString(key));
	            }
	        }
			List<NameValuePair> pairs = new ArrayList<NameValuePair>();  
			if (json != null && !json.isEmpty()) {
				Set<String> set = json.keySet();
				for (String key:set){
	    			pairs.add(new BasicNameValuePair(key, json.getString(key)));  
	            }
	        }
			request.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
			CloseableHttpResponse response = httpclient.execute(request);
			return EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * post请求
	 */
	public static String httpPost(String url, JSONObject json, JSONObject reqHeader){
		try {
        	//自定义HttpClient 设置CookieStore
			CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost request = new HttpPost(url);
            //设置Content-Type
            request.setHeader("Content-Type", "application/json");
			request.setConfig(requestConfig);
	        if (reqHeader != null && !reqHeader.isEmpty()) {
				Set<String> set = reqHeader.keySet();
				for (String key:set){
					request.setHeader(key,reqHeader.getString(key));
				}
	        }
			
            request.setEntity(new StringEntity(json.toString(), "UTF-8"));
			CloseableHttpResponse response = httpclient.execute(request);
			return EntityUtils.toString(response.getEntity(), "UTF-8");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}
}
